<!DOCTYPE html>
{% extends "base.html" %}

{% block title %}
    部门管理
{% endblock %}

{% block head %}
{% endblock %}

{% block content %}
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>部门信息管理表</legend>
    </fieldset>
    <div class="layui-row" style="text-align: center">
        <table class="layui-hide layui-anim layui-anim-fadein" id="test" lay-filter="test">

        </table>
    </div>

    <div style="margin: 5%; display: none" id="add_info_form">
        <form class="layui-form" id="add_form" method="post" lay-filter="example">
            <div class="layui-form-item">
                <label class="layui-form-label">部门名</label>
                <div class="layui-input-block">
                    <input type="text" id="department_name_form" name="bid" lay-verify="title" autocomplete="off"
                           placeholder="请输入部门名" class="layui-input">
                </div>
            </div>
        </form>
    </div>
    <div style="height: 100px; margin: 5%; display: none" id="search_info_form">
        <form class="layui-form" id="search_forms" method="post" lay-filter="example">
            <div class="layui-form-item">
                <label class="layui-form-label">筛选值</label>
                <div class="layui-input-block">
                    <select id="search_selector" lay-filter="search_list">
                        <option value=""></option>
                        <option value="1">部门ID</option>
                        <option value="2">部门名</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">搜索值</label>
                <div class="layui-input-block">
                    <input type="text" id="search_form" name="bid" lay-verify="title" autocomplete="off"
                           placeholder="请输入信息" class="layui-input">
                </div>
            </div>
        </form>
    </div>
    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm  layui-btn-warm" lay-event="addData">添加信息</button>
            <button class="layui-btn layui-btn-sm  layui-btn-normal" lay-event="seekData">查找信息</button>
            <button class="layui-btn layui-btn-sm  layui-btn-danger" lay-event="mutidelData">多项删除</button>
            <button class="layui-btn layui-btn-sm  layui-btn" lay-event="showData">显示全部数据</button>
        </div>
    </script>

    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-sm" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">删除</a>
    </script>
{% endblock %}

{% block script %}
    <script>
        var table = layui.table;
        var $ = layui.jquery;
        var form = layui.form;
        var table_data;
        var page_limit = 20;
        var data_length;
        var option = {
            elem: '#test'
            , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]
            , title: '部门数据表'
            , cellMinWidth: 80
            , data: ""
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {type: 'numbers', title: '序号', align: 'center', fixed: 'left'}
                , {field: 'DepartmentID', title: '部门ID', align: 'center', fixed: 'left', sort: true}
                , {field: 'DepartmentName', title: '所属部门', align: 'center'}
                , {field: 'CreateTime', title: '加入时间', align: 'center', sort: true}
                , {field: 'RowTools', fixed: 'right', title: '操作', align: 'center', toolbar: '#barDemo'}
            ]]
            , page: true
            , limit: 20
            , id: 'department_table'
        };

        load_table();

        $('#departments').addClass('layui-this');

        function load_table() {
            var index = layer.load(1);
            $.ajax({
                url: '{{ url_for('main_api.get_department_all_info') }}',
                type: 'GET',
                async: true,
                success: function (res) {
                    if (res.code === '200' || res.code === '2001') {
                        var data = res.data;
                        load_rows(data);
                        layer.close(index);
                    } else {
                        layer.msg(res.msg);
                        layer.close(index);
                    }
                },
                error: function f(res) {
                    alert("请求失败！状态码：" + res.status);
                    layer.close(index);
                }
            })
        }

        function load_rows(data) {
            var table = layui.table;
            table_data = data;
            data_length = data.length;
            option['data'] = data;
            table.render(option);
            set_edit_button_ID();
        }

        function load_department_selection(department_list) {
            var $selector = $('#departments_selector');
            for (var i = 0; i < department_list.length; i++) {
                $selector.append($('<option value="' + i + '">' + department_list[i] + '</option>'));
            }
        }

        function set_edit_button_ID() {
            for (var i = 0; i < data_length; i++) {
                $('tr[data-index=' + i + ']  td[data-field="RowTools"] a[lay-event="edit"]').prop('id', 'edit_button_' + i);
            }
        }

        function set_table_unedit() {
            for (var i = 0; i < option['cols'][0].length; i++) {
                if (option['cols'][0][i]['field'] === 'DepartmentName') {
                    delete option['cols'][0][i]['edit'];
                }
            }
            table.render(option);
        }

        function abandon_edit(obj) {
            var rowIndex = $(obj.tr).attr("data-index");
            set_table_unedit();
            load_table();
            $(".layui-table tbody tr").eq(rowIndex).css("background-color", "");
            $('#edit_button_' + rowIndex).text("编辑");
            $('#edit_button_' + rowIndex).attr('lay-event', 'edit');
            layer.msg('取消编辑状态');
        }

        !function (obj) {
            var delete_datas = [];
            table.on('checkbox(test)', function (obj) {
                if (obj.checked) {
                    if (obj.type === 'all') {
                        delete_datas = [];
                        var length = table_data.length > page_limit ? page_limit : table_data.length;
                        for (var i = 0; i < length; i++) {
                            var data = table_data;
                            delete data[i]['LAY_TABLE_INDEX'];
                            delete data[i]['LAY_CHECKED'];
                            delete_datas.push({'index': JSON.stringify(i), 'data': data[i]});
                        }
                        {#console.log(delete_datas);#}
                    } else {
                        var rowIndex = $(obj.tr).attr("data-index");
                        delete_datas.push({'index': rowIndex, 'data': obj.data}); // 获取表格中选中行的数据
                        console.log(delete_datas);
                    }
                } else {
                    if (obj.type === 'all') {
                        delete_datas = [];
                        {#console.log(delete_datas);#}
                    } else {
                        var rowIndex = $(obj.tr).attr("data-index");
                        for (var i = 0; i < delete_datas.length; i++) {
                            if (delete_datas[i]['index'] === rowIndex) {
                                delete_datas.splice(i, 1);
                            }
                        }
                        {#console.log(delete_datas);#}
                    }
                }
            });

            //头工具栏事件
            table.on('toolbar(test)', function (obj) {
                switch (obj.event) {
                    case 'addData':
                        var dpt_name;
                        layer.open({
                            type: 1,
                            title: "人员信息",
                            btn: ['确定', '取消'],
                            shadeClose: true,
                            shade: 0,
                            area: ['300px', '200px'],
                            content: $("#add_info_form"),
                            success: function (layero, index) {
                                $('#department_name_form').val("");
                            },
                            yes: function (ind) {
                                var index = layer.load(1);
                                dpt_name = $('#department_name_form').val();
                                $.ajax({
                                    url: '{{ url_for('main_api.add_department_info') }}',
                                    type: 'POST',
                                    async: true,
                                    data: {'DepartmentName': dpt_name},
                                    success: function (res) {
                                        if (res.code === '200') {
                                            load_table();
                                            layer.msg('添加部门信息成功!');
                                            layer.close(index);
                                            layer.close(ind);
                                            $('#add_info_form').css('display', 'none');
                                        } else {
                                            layer.msg(res.msg);
                                            layer.close(index);
                                        }
                                    },
                                    error: function f(res) {
                                        alert("请求失败！状态码：" + res.status);
                                        layer.close(index);
                                    }
                                })
                            },
                            btn2: function (ind) {
                                layer.close(ind);
                                $('#add_info_form').css('display', 'none');
                            },
                            cancel: function () {
                                $('#add_info_form').css('display', 'none');
                            }
                        });
                        break;
                    case 'seekData':
                        var tag_name, keyword;
                        layer.open({
                            type: 1,
                            title: "查找信息",
                            btn: ['查找'],
                            shadeClose: true,
                            shade: 0,
                            area: ['400px', '350px'],
                            content: $("#search_info_form"),
                            success: function (layero, index) {
                                $('#search_selector').val("");
                                $('#search_form').val("");
                                form.render('select')
                                form.on('select(search_list)', function (data) {
                                    tag_name = data.elem[data.elem.selectedIndex].text;
                                });
                            },
                            yes: function (ind) {
                                var index = layer.load(1);
                                keyword = $('#search_form').val();
                                $('#search_info_form').css('display', 'none');
                                $.ajax({
                                    url: '{{ url_for('main_api.get_department_info_by_tags') }}',
                                    type: 'GET',
                                    async: true,
                                    data: {'tag': tag_name, 'keyword': keyword},
                                    success: function (res) {
                                        if (res.code === '200') {
                                            var data = res.data;
                                            option['data'] = data;
                                            table_data = data;
                                            table.render(option);
                                            layer.msg('共查找到' + data.length + '条记录');
                                            layer.close(index);
                                        } else {
                                            layer.msg(res.msg);
                                            layer.close(index);
                                        }
                                    },
                                    error: function f(res) {
                                        alert("请求失败！状态码：" + res.status);
                                        layer.close(index);
                                    }
                                });
                                layer.close(ind);
                            },
                            cancel: function () {
                                $('#search_info_form').css('display', 'none');
                            }
                        })
                        break;
                    case 'showData':
                        load_table();
                        break;
                    case'mutidelData':
                        layer.confirm('真的删除所有行吗', function (index) {
                            var ind = layer.load(1);
                            if (JSON.stringify(delete_datas) === '[]' || JSON.stringify(delete_datas[0]['data']) === '{}') {
                                layer.close(index);
                                layer.msg('勾选左侧多选框删除多项数据');
                                layer.close(ind);
                            } else {
                                $.ajax({
                                    url: '{{ url_for('main_api.delete_department_info_list')}}',
                                    type: 'POST',
                                    async: true,
                                    data: {'data': JSON.stringify(delete_datas)},
                                    success: function (res) {
                                        if (res.code === '200') {
                                            layer.msg('删除用户数据成功!');
                                            load_table();
                                            layer.close(ind);
                                            layer.close(index);
                                        } else {
                                            layer.msg(res.msg);
                                            layer.close(ind);
                                            layer.close(index);
                                        }
                                    },
                                    error: function f(res) {
                                        alert("请求失败！状态码：" + res.status);
                                        layer.close(index);
                                    }
                                });
                            }

                        });
                        break;
                }
            });

            //监听行工具事件
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                var rowIndex;
                if (obj.event === 'del') {
                    layui.use(['layer', 'jquery'], function () {
                        var layer = layui.layer;
                        var element = layui.element;
                        layer.open({
                            title: "删除信息",
                            btn: ['确定', '取消'],
                            shadeClose: true,
                            shade: 0.3,
                            content: "确认删除?",
                            yes: function (ind) {
                                var index = layer.load(1);
                                $.ajax({
                                    url: '{{ url_for('main_api.delete_department_info')}}',
                                    type: 'POST',
                                    async: true,
                                    data: {'DepartmentID': data.DepartmentID},
                                    success: function (res) {
                                        if (res.code == '200') {
                                            layer.msg('删除用户数据成功!');
                                            for(var i = 0;i < table_data.length;i++){
                                                if(table_data[i]['DepartmentID'] === data['DepartmentID']){
                                                    table_data.splice(i, 1);
                                                }
                                            }
                                            option['data'] = table_data;
                                            obj.del();
                                            element.render('table');
                                            table.render(option);
                                            layer.close(ind);
                                            layer.close(index);
                                        } else {
                                            layer.msg(res.msg);
                                            layer.close(index);
                                        }
                                    },
                                    error: function f(res) {
                                        alert("请求失败！状态码：" + res.status);
                                        layer.close(index);
                                    }
                                });
                            },
                            btn2: function () {
                                var rowIndex = $(obj.tr).attr("data-index");
                                $(".layui-table tbody tr").eq(rowIndex).removeClass("layui-table-click");
                                $(obj.tr[1]).removeClass("layui-table-click");
                                $(obj.tr[0]).removeClass("layui-table-click");
                            },
                            cancel: function () {
                                var rowIndex = $(obj.tr).attr("data-index");
                                $(".layui-table tbody tr").eq(rowIndex).removeClass("layui-table-click");
                                $(obj.tr[1]).removeClass("layui-table-click");
                                $(obj.tr[0]).removeClass("layui-table-click");
                            }
                        })
                    })

                } else if (obj.event === 'edit') {
                    var click_time = 0;
                    table.on('row(test)', function (obj) {
                        click_time++;
                        if (click_time === 1) {
                            rowIndex = $(obj.tr).attr("data-index");
                            $(".layui-table tbody tr").eq(rowIndex).css("background-color", "lightgrey");
                            $('#edit_button_' + rowIndex).text("取消编辑");
                            $('#edit_button_' + rowIndex).attr('lay-event', 'unedit');
                        }
                    });
                    for (var i = 0; i < option['cols'][0].length; i++) {
                        if (option['cols'][0][i]['field'] === 'DepartmentName') {
                            option['cols'][0][i]['edit'] = 'text';
                        }
                    }
                    table.render(option);
                    set_edit_button_ID();
                    layer.msg('部门名已转换到可编辑状态');
                    table.on('edit(test)', function (result) {
                        layer.confirm('是否保存已编辑内容', {btn: ['保存', '取消']}, function (index) {
                            var data = result.data; //得到所在行所有键值
                                                    //得到字段
                            var update_data = {
                                'DepartmentID': data.DepartmentID,
                                'DepartmentName': data.DepartmentName
                            };
                            layer.msg('检验输入数据是否有效...');
                            $.ajax({
                                url: '{{ url_for('main_api.edit_department_info') }}',
                                type: 'POST',
                                data: update_data,
                                async: true,
                                success: function (res) {
                                    if (res.code === '200') {
                                        layer.msg('修改成功!');
                                        set_table_unedit();
                                        set_edit_button_ID();
                                        $(".layui-table tbody tr").eq(rowIndex).css("background-color", "");
                                    } else {
                                        layer.msg(res.msg);
                                        load_table();
                                        layer.close(index);
                                    }
                                },
                                error: function f(res) {
                                    alert("请求失败！状态码：" + res.status);
                                    layer.close(index);
                                }
                            })
                        }, function (index) {
                            abandon_edit(obj);
                            layer.close(index);
                        });

                    })
                } else if (obj.event === 'unedit') {
                    var click_time = 0;
                    table.on('row(test)', function (obj) {
                        click_time++;
                        if (click_time === 1) {
                           abandon_edit(obj);
                        }
                    })
                }
            });
        }();
    </script>
{% endblock %}